/**
 * 状态管理调试工具
 * 用于验证Pinia和localStorage状态同步的一致性
 */

import { useUserStore } from '../stores/user'

/**
 * 检查状态一致性
 */
export function checkStateConsistency() {
  const userStore = useUserStore()
  
  // 获取Pinia状态
  const piniaState = {
    isLoggedIn: userStore.isLoggedIn,
    currentUser: userStore.currentUser,
    isInitialized: userStore.isInitialized
  }
  
  // 获取localStorage状态
  const localStorageState = {
    token: localStorage.getItem('token'),
    refreshToken: localStorage.getItem('refreshToken'),
    userInfo: localStorage.getItem('userInfo')
  }
  
  // 解析userInfo
  let parsedUserInfo = null
  try {
    parsedUserInfo = localStorageState.userInfo ? JSON.parse(localStorageState.userInfo) : null
  } catch (error) {
    console.error('解析localStorage中的userInfo失败:', error)
  }
  
  // 检查一致性
  const hasToken = !!localStorageState.token
  const hasUserInfo = !!parsedUserInfo
  const piniaLoggedIn = piniaState.isLoggedIn
  
  const isConsistent = (hasToken && hasUserInfo) === piniaLoggedIn
  
  const report = {
    consistent: isConsistent,
    pinia: piniaState,
    localStorage: {
      ...localStorageState,
      parsedUserInfo
    },
    analysis: {
      hasToken,
      hasUserInfo,
      piniaLoggedIn,
      shouldBeLoggedIn: hasToken && hasUserInfo
    }
  }
  
  console.log('=== 状态一致性检查报告 ===')
  console.log('一致性:', isConsistent ? '✅ 一致' : '❌ 不一致')
  console.log('详细信息:', report)
  
  if (!isConsistent) {
    console.warn('⚠️ 检测到状态不一致，建议执行状态同步')
    console.log('修复建议:')
    if (hasToken && hasUserInfo && !piniaLoggedIn) {
      console.log('- 执行 userStore.syncFromStorage() 同步状态')
    } else if (!hasToken && piniaLoggedIn) {
      console.log('- 执行 userStore.logout() 清除状态')
    }
  }
  
  return report
}

/**
 * 强制同步状态
 */
export function forceSyncState() {
  const userStore = useUserStore()
  console.log('🔄 强制同步状态...')
  
  const success = userStore.syncFromStorage()
  
  if (success) {
    console.log('✅ 状态同步成功')
  } else {
    console.log('❌ 状态同步失败，清除状态')
  }
  
  // 再次检查一致性
  setTimeout(() => {
    checkStateConsistency()
  }, 100)
}

/**
 * 模拟登录状态
 */
export function simulateLogin() {
  const userStore = useUserStore()
  
  const mockUserInfo = {
    id: 1,
    username: 'testuser',
    nickname: '测试用户',
    email: 'test@example.com',
    role: 'USER',
    roles: ['USER']
  }
  
  const mockToken = 'mock-token-' + Date.now()
  const mockRefreshToken = 'mock-refresh-token-' + Date.now()
  
  console.log('🧪 模拟登录...')
  userStore.login(mockUserInfo, mockToken, mockRefreshToken)
  
  setTimeout(() => {
    checkStateConsistency()
  }, 100)
}

/**
 * 模拟登出
 */
export function simulateLogout() {
  const userStore = useUserStore()
  
  console.log('🚪 模拟登出...')
  userStore.logout()
  
  setTimeout(() => {
    checkStateConsistency()
  }, 100)
}

/**
 * 监听状态变化
 */
export function watchStateChanges() {
  const userStore = useUserStore()
  
  // 监听Pinia状态变化
  userStore.$subscribe((mutation, state) => {
    console.log('📊 Pinia状态变化:', {
      type: mutation.type,
      storeId: mutation.storeId,
      payload: mutation.payload,
      newState: {
        isLoggedIn: state.isLoggedIn,
        userId: state.currentUser.id,
        username: state.currentUser.username
      }
    })
    
    // 延迟检查一致性
    setTimeout(() => {
      checkStateConsistency()
    }, 50)
  })
  
  // 监听localStorage变化
  window.addEventListener('storage', (event) => {
    if (['token', 'refreshToken', 'userInfo'].includes(event.key)) {
      console.log('💾 localStorage变化:', {
        key: event.key,
        oldValue: event.oldValue,
        newValue: event.newValue
      })
      
      // 延迟检查一致性
      setTimeout(() => {
        checkStateConsistency()
      }, 50)
    }
  })
  
  console.log('👀 开始监听状态变化...')
}

/**
 * 添加调试命令到全局
 */
export function addStateDebugCommands() {
  if (typeof window !== 'undefined') {
    window.stateDebug = {
      check: checkStateConsistency,
      sync: forceSyncState,
      login: simulateLogin,
      logout: simulateLogout,
      watch: watchStateChanges
    }
    
    console.log('🛠️ 状态调试工具已添加到 window.stateDebug')
    console.log('可用命令:')
    console.log('- window.stateDebug.check() - 检查状态一致性')
    console.log('- window.stateDebug.sync() - 强制同步状态')
    console.log('- window.stateDebug.login() - 模拟登录')
    console.log('- window.stateDebug.logout() - 模拟登出')
    console.log('- window.stateDebug.watch() - 监听状态变化')
  }
}

// 开发环境自动添加调试命令
if (import.meta.env.DEV) {
  addStateDebugCommands()
}
